package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.Md5encode;

import model.Item;

import common.Constant;

public class TmpSearchDao extends RpDao{

	public List<Item> getSearchCache(List<String> tags,int index,List<Integer>  totalPage ){
		Connection conn=this.getConn();
		List<Item> items = new ArrayList<Item>();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt=conn.prepareStatement(SqlString.selectTmp_search);
			pstmt.setString(1, Md5encode.getMD5ofStr(tags.toString()));
			pstmt.setInt(2, Constant.SearchCacheExpired);
			rs=pstmt.executeQuery();
			
			if(rs.next()){
				String itemids=rs.getString("itemids");
				rs.close();
				String[] itemidlist=itemids.split(",");
				totalPage.add((itemidlist.length-1)/Constant.PageSize );
				ItemDao itemdao=new ItemDao();
				for(int i=index*Constant.PageSize;i<(index+1)*Constant.PageSize && i<itemidlist.length;i++){
					items.add(itemdao.query(Integer.valueOf(itemidlist[i])));
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		this.closeDao(conn,pstmt, rs);
		}
		return items;
	}
	
	public void saveSearchResult(String tags,List<Item> items){
		Connection conn=this.getConn();
		if(items.size()==0)
			return;		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String itemids="";
		String keyid=Md5encode.getMD5ofStr(tags);
		for(int i=0;i<items.size();i++){
			Item item=items.get(i);
			itemids+=item.getId()+",";
		}
		
		if (itemids.length()>0)
			itemids=itemids.substring(0,itemids.length()-1);
		
		try {
//			insertTmp_search="insert into tmp_search(keyid,tags,itemids,mtime) values(?,?,?,now())on duplicate key update  itemids=?,mtime=now()",
			pstmt=conn.prepareStatement(SqlString.insertTmp_search);
			int i=1;
			System.out.println();
			pstmt.setString(i++, keyid);
			pstmt.setString(i++, tags);
			pstmt.setString(i++, itemids);
			
			pstmt.setString(i++, itemids);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		this.closeDao(conn,pstmt, rs);
		}
	}
	
}
